package com.gxuwz.leave.servlet;

import com.gxuwz.leave.context.AppContext;
import com.gxuwz.leave.entity.User;
import com.gxuwz.leave.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/index")
public class IndexServlet extends BaseHttpServlet{
    private final static String VIEW_LOGIN = "/login";
    private final static String USER_MAIN = "WEB-INF/views/index/user_index.jsp";
    private final static String INST_MAIN = "WEB-INF/views/index/inst_index.jsp";

    private final static String STU_MAIN = "WEB-INF/views/index/stu_index.jsp";

    //问题记录，这里用@Autowired不行
    private UserService userService;

    @Override
    public void init() throws ServletException {
        super.init();
        userService = AppContext.getBean(UserService.class);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String identity = (String) req.getSession().getAttribute("identity");
        String userid = (String) req.getSession().getAttribute("userID");
        if(userid==null){
            super.doRedirect(req, resp, req.getContextPath()+VIEW_LOGIN);
        }else{
            if("user".equals(identity)){
                super.doDispatch(req, resp, USER_MAIN);
            }else if("instructor".equals(identity)){
                super.doDispatch(req, resp, INST_MAIN);
            }else if("student".equals(identity)){
                super.doDispatch(req, resp, STU_MAIN);
            }else{
                super.doRedirect(req, resp, req.getContextPath()+VIEW_LOGIN);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = new User();
        user.setUserid(req.getParameter("userid"));
        user.setFullname(req.getParameter("fullname"));
        user.setPassword(req.getParameter("password"));
        user.setTelephone(req.getParameter("telephone"));
        userService.editUser(user);
        //清除session，退出登录
        req.getSession().invalidate();
        //重定向退出登录，直接退出选择
        super.doRedirect(req, resp, req.getContextPath() + "/login");
        System.out.println("要导向的页面是"+req.getContextPath() + "/login");
    }
}
